﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.Common;
using Microsoft.Practices.EnterpriseLibrary.Data;
using DuJianliang.ApplicationPlatform.Common;
using DuJianliang.ApplicationPlatform.UserPermission;

namespace DuJianliang.ApplicationPlatform.Proj5715.Process
{
    public partial class DispatchList : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                BindGridView();
            }
        }

        private void BindGridView()
        {
//            string sql = @"SELECT A.*, C.FlowID, B.StepID, B.StepName, B.OperationName, B.OperationDate, B.OperatorInfo, B.Completed, B.CreateDate AS FlowCreateDate
//                            FROM dbo.t5715_Dispatch A 
//                            LEFT JOIN dbo.FlowInstance B ON A.FlowInstanceID = B.FlowInstanceID
//                            LEFT JOIN dbo.FlowMain C ON C.TableName = 't5715_Dispatch'
//                            ORDER BY CreateDate DESC";

//            Database database = DatabaseFactory.CreateDatabase();
//            DbCommand dbCommand = database.GetSqlStringCommand(sql);
//            DataTable dataTable = database.ExecuteDataSet(dbCommand).Tables[0];

            string sql = @"SELECT A.*, B.StepID, B.StepName, B.OperationName, B.OperationDate, B.OperatorInfo, B.Completed, B.CreateDate AS FlowCreateDate
                            ,
                            (
                              SELECT TOP 1 FSR.FlowID FROM dbo.FlowStepRelation FSR 
                              INNER JOIN dbo.FlowStepOperator FSO ON FSR.StepID = FSO.StepID
                              INNER JOIN dbo.FlowMain FM ON FSR.FlowID = FM.FlowID AND FM.TableName = 't5715_Dispatch'
                              WHERE FSR.ParentID IS NULL AND FSO.OperatorInfo = @OperatorInfo
                            ) AS FlowID
                            FROM dbo.t5715_Dispatch A 
                            LEFT JOIN dbo.FlowInstance B ON A.FlowInstanceID = B.FlowInstanceID
                            ORDER BY CreateDate DESC";

            Database database = DatabaseFactory.CreateDatabase();
            DbCommand dbCommand = database.GetSqlStringCommand(sql);
            database.AddInParameter(dbCommand, "@OperatorInfo", DbType.String, CurrentInfo.Instance.CurrentUser.UserName);
            DataTable dataTable = database.ExecuteDataSet(dbCommand).Tables[0];

            UserPermissionBll userPermissionBll = new UserPermissionBll();
            if (userPermissionBll.HasPermission(CurrentInfo.Instance.CurrentUser.ID, (int)Permission.ViewDispatch))
            {
                gvReimb.DataSource = dataTable;                
            }
            else
            {
                //用户只能看到自己车间负责的派工单, 检验人员可以看到可检验的派工单

                DataTable dataTable2 = dataTable.Clone();                
                ProcessDal processDal = new ProcessDal();                

                foreach (DataRow dataRow in dataTable.Rows)
                {
                    string missileModel = dataRow["MissileModel"].ToString();

                    // true表示该派工单当前用户可以检验，false表示不可以检验
                    bool canCheckProcess = false;

                    // 根据导弹型号获取工序负责部门的ID
                    DataTable deptDataTable = processDal.GetDeptIDByMissileModel(missileModel);

                    // 遍历部门ID，查看当前用户是否可检验
                    foreach (DataRow dr in deptDataTable.Rows)
                    {
                        canCheckProcess = processDal.CanCheckProcess(CurrentInfo.Instance.CurrentUser.ID, dr["DeptID"].ToString());

                        if (canCheckProcess)
                        {
                            dataTable2.Rows.Add(dataRow.ItemArray);
                            break;
                        }
                    }

                    // 如果为false表示该派工单当前用户不能进行检验，此时执行下面的代码：用户只能看到自己车间负责的派工单
                    if (canCheckProcess)
                    {
                        continue;
                    }

                    DataTable workShopDataTable = processDal.GetIssueWorkShop(missileModel);
                    List<DeptOB> deptOBList = new List<DeptOB>();

                    DeptOB userDeptOB = CurrentInfo.Instance.CurrentUser.Dept;
                    
                    switch (userDeptOB.DeptLevel)
                    {
                        case "1" :
                            deptOBList = userPermissionBll.GetChildDeptID(userDeptOB.DeptID);
                            break;
                        case "2" :
                            deptOBList.Add(userDeptOB);
                            break;
                        case "3" :
                            deptOBList.Add(userPermissionBll.GetDeptByID(userDeptOB.ParentDeptID));
                            break;
                    }

                    foreach (UserPermission.DeptOB deptOB in deptOBList)
                    {
                        DataRow[] dataRows = workShopDataTable.Select(string.Format("DeptID='{0}'", deptOB.DeptID));
                        if (dataRows.Length > 0)
                        {
                            dataTable2.Rows.Add(dataRow.ItemArray);
                            break;
                        }
                    }
                }

                gvReimb.DataSource = dataTable2;
            }
            
            gvReimb.DataBind();
        }

        protected void btnCreate_Click(object sender, EventArgs e)
        {
            Response.Redirect("DispatchEdit.aspx?Source=list");
        }

        protected void gvReimb_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (string.IsNullOrWhiteSpace(e.CommandName) || e.CommandName.ToLower().Equals("page"))
            {
                return;
            }

            GridViewRow gridViewRow = ((GridViewRow)(((Button)(e.CommandSource)).Parent.Parent));
            string flowInstanceID = gvReimb.DataKeys[gridViewRow.RowIndex]["FlowInstanceID"].ToString();           

            switch (e.CommandName)
            { 
                case "CmdEdit" :
                    Response.Redirect(string.Format("DispatchEdit.aspx?flowInstanceID={0}&Source=list", flowInstanceID));
                    break;
                case "CmdShowFlow" :
                    BindGridView();
                    break;
                case "CmdDelete" :
                    ProcessDal dal = new ProcessDal();
                    dal.Dispatch_Delete(flowInstanceID);
                    BindGridView();
                    break;
                default:
                    break;
            }
        }

        protected void gvReimb_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                string flowID = gvReimb.DataKeys[e.Row.RowIndex]["FlowID"].ToString();
                string flowInstanceID = gvReimb.DataKeys[e.Row.RowIndex]["FlowInstanceID"].ToString();

                TableCell tableCell_IssueState = e.Row.Cells[6];
                string issueState = tableCell_IssueState.Text.ToLower();
                switch (issueState)
                {
                    case "true":
                        tableCell_IssueState.Text = "已下达";                        
                        break;
                    default:
                        tableCell_IssueState.Text = "未下达";
                        break;
                }

                TableCell tableCell_DispatchState = e.Row.Cells[9];
                string dispatchState = tableCell_DispatchState.Text;
                switch (dispatchState)
                {
                    case "1":
                        tableCell_DispatchState.Text = "已完成";
                        break;
                    default:
                        tableCell_DispatchState.Text = "未完成";
                        break;
                }

                TableCell tableCell_FlowCompleted = e.Row.Cells[10];
                string flowCompleted = tableCell_FlowCompleted.Text.ToLower();
                switch (flowCompleted)
                { 
                    case "true" :
                        tableCell_FlowCompleted.Text = "已完成";
                        e.Row.BackColor = System.Drawing.Color.LightGreen;
                        break;
                    case "false" :
                        tableCell_FlowCompleted.Text = "处理中";
                        e.Row.BackColor = System.Drawing.Color.Pink;
                        break;
                    default:
                        tableCell_FlowCompleted.Text = "无";
                        break;
                }

                Button btnFlow = e.Row.Cells[11].FindControl("btnFlow") as Button;
                if (btnFlow != null)
                {                   
                    string url = string.Format("/Flow/FlowManager.aspx?FlowID={0}&FlowInstanceID={1}", flowID, flowInstanceID);
                    btnFlow.Attributes.Add("onclick", string.Format("showPage('{0}');", url));
                }

                Button btnDelete = e.Row.Cells[11].FindControl("btnDelete") as Button;
                if (btnDelete != null)
                {

                    if (!FlowHelper.HasFlowData(new Guid(flowInstanceID)))
                    {
                        btnDelete.Attributes.Add("onclick", "javascript:return confirm('确定要删除吗?')");
                    }
                    else
                    {
                        btnDelete.Visible = false;
                    }    
                }                            
            }
        }
    }
}